/**
 * @author [siwi]
 * @email [siwi@siwi.me]
 * @create date 2017-05-30 04:51:44
 * @modify date 2017-05-30 04:51:44
 * @desc [description]
*/
const jwt = require( 'jsonwebtoken' )
const Conf = require( '../config/config' )
const Tools = require( '../libs/tools' )
module.exports = async( ctx, next ) => {
  const authorization = ctx.req.headers.Authorization || ctx.req.headers.authorization
  const bearer = /^Bearer .+/
  if ( !bearer.test( authorization ) ) ctx.throw( 'Token 格式不配备' )
  const token = authorization.replace( /^Bearer /, '' )
  // 解密 token 获取jwt jwt 默认base64 不安全
  const jwt_token = Tools.decrypted( token ) || false
  let decode = jwt.verify( jwt_token, Conf.jwtSecret )
  ctx.authuser = decode
  ctx.token = token
  ctx.jwt_token = jwt_token
  return next()
}